//
//  JYJMusicPlayerViewController.m
//  HappyListen
//
//  Created by 冀永金 on 16/9/6.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJMusicPlayerViewController.h"
#import "JYJMusicPlayerView.h"
#import "JYJProgramModel.h"
#import "JYJMusicPlayerTools.h"
#import "JYJDataTools.h"
#import "UIImageView+WebCache.h"
#import "JYJTAMacro.h"
#import "BaseButton.h"
#import "Masonry.h"
#import "LSPaoMaView.h"
#import "JYJMusicsContentModel.h"
#import "UMSocial.h"
#import "JYJMusicMiniView.h"
#import "JYJVCOfFeaturedTopThreeDetails.h"
#import "JYJFeaturedDetailsSmallCollectionCell.h"
#import "JYJMusicManager.h"
@interface JYJMusicPlayerViewController ()<JYJMusicPlayerToolsDelegate,UMSocialUIDelegate>
@property (nonatomic, strong) JYJMusicPlayerView *playView;
@property (nonatomic, strong) JYJMusicPlayerTools *playerTools;
@property (nonatomic, strong) UIImageView *imageOfShare;
@property (nonatomic, strong) BaseButton *buttonOfShare;
@property (nonatomic, strong) UIView *colorView;
@property (nonatomic, strong) BaseButton *buttonOfCollect;
@property (nonatomic, strong) LSPaoMaView *paoma;

@property (nonatomic, strong) UIImageView *pinglunImage;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIButton *expressionOfButton;
@property (nonatomic, strong) UIButton *publishButton;
@property (nonatomic, strong) UIImageView *imageOfAnimation;
@property (nonatomic, strong) NSMutableArray *marr;
@end

@implementation JYJMusicPlayerViewController
+(instancetype)shareMusicPlayerVC {
    static JYJMusicPlayerViewController *playerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[JYJMusicPlayerViewController alloc]init];
    });
    return playerVC;
}
- (void)loadView {
    [super loadView];
    self.playView = [[JYJMusicPlayerView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_playView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    // 动画
    [self createAnimation];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"community_more"] style:UIBarButtonItemStylePlain target:self action:@selector(handleMore:)];
    
    self.playerTools = [JYJMusicPlayerTools shareMusicPlayerTools];
    self.playerTools.delegate = self;
   
    
    self.imageOfShare = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"play_right_bubble"]];
    self.imageOfShare.userInteractionEnabled = YES;
    [self.playView addSubview:_imageOfShare];
    [self.imageOfShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(5);
        make.right.equalTo(self.view.mas_right).with.offset(-10);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(102);
    }];
    self.imageOfShare.hidden = YES;
    self.buttonOfShare = [BaseButton buttonWithType:UIButtonTypeSystem];
    [self.imageOfShare addSubview:_buttonOfShare];
    [self.buttonOfShare setTitle:@"分享" forState:UIControlStateNormal];
    [self.buttonOfShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageOfShare.mas_top).with.offset(10);
        make.left.equalTo(self.imageOfShare.mas_left).with.offset(20);
        make.right.equalTo(self.imageOfShare.mas_right).with.offset(-20);
        make.height.mas_equalTo(40);
    }];
    [self.buttonOfShare setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.buttonOfShare addTarget:self action:@selector(handleShare) forControlEvents:UIControlEventTouchUpInside];
    self.buttonOfShare.titleLabel.font = [UIFont systemFontOfSize:20];
    self.colorView = [[UIView alloc]init];
    [self.imageOfShare addSubview:_colorView];
    _colorView.backgroundColor = [UIColor colorWithRed:0.33 green:0.33 blue:0.38 alpha:1.00];
    [self createBottomViews];
    [self.colorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonOfShare.mas_bottom).with.offset(2);
        make.left.equalTo(self.imageOfShare.mas_left).with.offset(0);
        make.right.equalTo(self.imageOfShare.mas_right).with.offset(0);
        make.height.mas_equalTo(2);

    }];
    self.buttonOfCollect = [BaseButton buttonWithType:UIButtonTypeSystem];
    [self.imageOfShare addSubview:_buttonOfCollect];
    [self.buttonOfCollect setTitle:@"举报" forState:UIControlStateNormal];
    [self.buttonOfCollect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.imageOfShare.mas_bottom).with.offset(-5);
        make.left.equalTo(self.imageOfShare.mas_left).with.offset(20);
        make.right.equalTo(self.imageOfShare.mas_right).with.offset(-20);
        make.height.mas_equalTo(40);
    }];
    [self.buttonOfCollect setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.buttonOfCollect.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.buttonOfCollect addTarget:self action:@selector(handleJuPao:) forControlEvents:UIControlEventTouchUpInside];
    // 为播放器添加观察者,观察播放速率"rate".
    // 因为AVPlayer没有一个内部属性来标识当前的播放状态.所以我们可以通过rate变相的得到播放状态.

    [self.playerTools.player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
   //回调事件 音乐播放 暂停 上下一曲
    [self.playView pause:^(UIButton *button) {
        // 根据AVPlayer的rate判断.
        if ([JYJMusicPlayerTools shareMusicPlayerTools].player.rate == 0) {
            [[JYJMusicPlayerTools shareMusicPlayerTools]playMusic];
            

        }else
        {
             [[JYJMusicPlayerTools shareMusicPlayerTools]pauseMusic];
            
        }
    }
        

    lastSong:^(UIButton *button) {
        if (self.modelIndex > 0) {
            self.modelIndex -- ;
        }else {
            self.modelIndex = [JYJDataTools shareDataTools].dataArray.count - 1;
        }
        [self player_Play];
    } nextSong:^(UIButton *button) {
        if (self.modelIndex == [JYJDataTools shareDataTools].dataArray.count - 1) {
            self.modelIndex = 0;
        }else {
            self.modelIndex ++ ;
        }
        [self player_Play];
    }];
    [self.playView slider:^(UISlider *slider) {
        // 图片变红
        self.playView.sliderView.frame = CGRectMake(0, 0, slider.value * CGRectGetWidth(self.playView.sliderBackImage.frame), 100);
        [[JYJMusicPlayerTools shareMusicPlayerTools]seekToTimeWithValue:slider.value];
    }];
    // Do any additional setup after loading the view.
}
#pragma mark--------------添加完观察者出发的事件！！！！
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"rate"]) {
        if ([[change valueForKey:@"new"] integerValue] == 0) {
            [self.playView.pauseButton setImage:[UIImage imageNamed:@"play_img"] forState:(UIControlStateNormal)];
            // 动画停止
            [self.imageOfAnimation stopAnimating];

            
        }else
        {
            [self.playView.pauseButton setImage:[UIImage imageNamed:@"pause_img"] forState:(UIControlStateNormal)];
            // 动画开始
            
             [_imageOfAnimation startAnimating];


        }
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"%ld",self.programModel.music_media.length)
    NSLog(@"%ld",self.modelIndex);
        if (self.programModel.music_media.length == 0) {
            NSURL *url = [NSURL fileURLWithPath: self.programModel.localPath];
            NSLog(@"%@",self.programModel.localPath);
        [JYJMusicPlayerTools shareMusicPlayerTools].playerItem= [[AVPlayerItem alloc]initWithURL:url];
            [[JYJMusicPlayerTools shareMusicPlayerTools] playMusic];
    
        }

           // 回调事件收藏 下载
    [self.playView  menu:^(UIButton *buttonOfImage) {
        [self.navigationController popViewControllerAnimated:YES];
    } support:^(UIButton *buttonOfImage) {
        
    } cancleSuppot:^(UIButton *buttonOfImage) {
        
    } downLoad:^(UIButton *buttonOfImage) {

      [[JYJMusicManager shared] startWithMusicModel:self.programModel];
        
    }];

    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(handleBack)];
    

    // 圆View隐藏
    [JYJMusicMiniView shareMiniView].hidden = YES;
    [self player_Play];
}

- (void)player_Play {
    //判断当前播放器的model和点击cell的index对应的model是不是同一个
    //如果是同一个，说明正在播放的和我们点击的是同一个，这是要重新播放，直接返回就可以了
   if ([[JYJMusicPlayerTools shareMusicPlayerTools].programModel isEqual:[[JYJDataTools shareDataTools] getModelWithIndex:self.modelIndex]]) {
            return;
        }
          // 如果播放中和我们点击不是同一个，那么替换当前播放器的model
        //重新准备播放
    [JYJMusicPlayerTools shareMusicPlayerTools].programModel = [[JYJDataTools shareDataTools]getModelWithIndex:self.modelIndex];
    
    
    
    // 背景图片
    [self.playView.bigBackImage sd_setImageWithURL:[NSURL URLWithString:[JYJMusicPlayerTools shareMusicPlayerTools].programModel.music_img] placeholderImage:PLACEHOLDERIMAGE];
    
    // 圆背景图片
    [[JYJMusicMiniView shareMiniView].music_img sd_setImageWithURL:[NSURL URLWithString:[JYJMusicPlayerTools shareMusicPlayerTools].programModel.music_img] placeholderImage:[UIImage imageNamed:@"MyCD"]];
    
    //跑马灯
        self.title = [JYJMusicPlayerTools shareMusicPlayerTools].programModel.music_title;
    // 圆图片点击进去的titile
    [JYJMusicMiniView shareMiniView].namelLabel.text = self.title;
    self.paoma = [[LSPaoMaView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 40) title:self.title BackColor:[UIColor clearColor] textColor:[UIColor whiteColor] textFont:20];
    self.navigationItem.titleView = _paoma;
   
       

        // !!!!注意这里是准备播放  不是播放！！
        [[JYJMusicPlayerTools shareMusicPlayerTools]preparePlayMusic];
   
    
}
- (void)getCurTime:(NSString *)curTime totle:(NSString *)totle progress:(CGFloat)progress {
    self.playView.progressTimeLabel.text = curTime;
    self.playView.totalTimeLabel.text = totle;
    self.playView.slider.value = progress;
    // 图片变红
    self.playView.sliderView.frame = CGRectMake(0, 0, progress * CGRectGetWidth(self.playView.sliderBackImage.frame), 100);
    
}
- (void)endPlayAction {
    
    if (self.modelIndex == [JYJDataTools shareDataTools].dataArray.count - 1) {
        self.modelIndex = 0;
    }else {
        self.modelIndex ++ ;
    }
    [self player_Play];

}
// 播放失败调用此方法  代理
- (void)playFail {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"节目加载失败" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];

}
- (void)handleMore:(UIBarButtonItem *)button {
    self.imageOfShare.hidden = NO;
    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"community_more"] style:UIBarButtonItemStylePlain target:self action:@selector(handle:)];
    
}
- (void)handle:(UIBarButtonItem *)button {
    self.imageOfShare.hidden = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"community_more"] style:UIBarButtonItemStylePlain target:self action:@selector(handleMore:)];
}
- (void)createBottomViews {
    self.pinglunImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"my_input_bg"]];
    _pinglunImage.userInteractionEnabled = YES;
    [self.playView addSubview:_pinglunImage];
    [self.pinglunImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.height.mas_equalTo(50);
    }];
    self.textField = [[UITextField alloc]init];
    [self.pinglunImage addSubview:_textField];
    _textField.placeholder = @"说点什么吧";
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.pinglunImage.mas_bottom).with.offset(-2);
        make.left.equalTo(self.view.mas_left).with.offset(5);
        make.top.equalTo(self.pinglunImage.mas_top).with.offset(2);
        make.width.mas_equalTo(SCREEN_WIDTH * 3 / 4);
    }];
    self.expressionOfButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.pinglunImage addSubview:_expressionOfButton];
    [self.expressionOfButton setImage:[UIImage imageNamed:@"play_down"] forState:UIControlStateNormal];
    [self.expressionOfButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.pinglunImage.mas_bottom).with.offset(-8);
        make.left.equalTo(self.textField.mas_right).with.offset(4);
        make.top.equalTo(self.pinglunImage.mas_top).with.offset(8);
        make.width.mas_equalTo(34);
    }];
    self.publishButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.pinglunImage addSubview:_publishButton];
    self.publishButton.backgroundColor = [UIColor orangeColor];
    [self.publishButton setTitle:@"发表" forState:UIControlStateNormal];
    self.publishButton.titleLabel.textAlignment = 1;
    [self.publishButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.publishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.expressionOfButton.mas_right).with.offset(4);
        make.top.equalTo(self.pinglunImage.mas_top).with.offset(5);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(40);
    }];
    self.publishButton.layer.cornerRadius = 5;
    self.publishButton.clipsToBounds = YES;
}
// 分享
- (void)handleShare {
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"57d654c467e58eb356002a73" shareText:@"你要分享的文字:" shareImage:[UIImage imageNamed:@"icon.png"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ,UMShareToRenren,UMShareToDouban,UMShareToEmail,UMShareToSms,UMShareToFacebook,UMShareToTwitter, nil ] delegate:self];
      self.imageOfShare.hidden = YES;
}
// 创建动画
- (void)createAnimation{
     self.imageOfAnimation = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"a1"]];
    [[JYJMusicMiniView shareMiniView] addSubview:_imageOfAnimation];
    [_imageOfAnimation mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo([JYJMusicMiniView shareMiniView].mas_top).with.offset(20);
        make.left.equalTo([JYJMusicMiniView shareMiniView].mas_left).with.offset(20);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    self.marr = [NSMutableArray array];
    for (int i = 1; i < 27; i++) {
        NSString *imageName = [NSString stringWithFormat:@"a%d",i];
        UIImage *image = [UIImage imageNamed:imageName];
        [_marr addObject:image];
    }
    _imageOfAnimation.animationDuration = .5;
    _imageOfAnimation.animationImages  = _marr;
    _imageOfAnimation.animationRepeatCount = 0;
   
    

}
- (void)handleJuPao:(BaseButton *)button {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"此服务尚未开通" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    [alert dismissViewControllerAnimated:YES completion:nil];
}
- (void)handleBack {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
    [self.playerTools.player removeObserver:self forKeyPath:@"rate"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
